package com.jc.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.UUID;

public class UserFactory {
	
	//INSERT INTO `jcyj_user_level_extend` (`user_id`, `user_level`, `parent_user_id`, `up_level_chain`, `create_time`, `update_time`) VALUES (33, 300, 3, '33', '2019-03-07 21:22:01', '2019-03-07 21:22:03');
	
	
	//INSERT INTO `temp_users`( `name`, `pid`, `status`,`level`) VALUES ( 'ere', 0, 1,300)
	
	
	
	public static int getUserLevel() {
		int[] levels = {50,100,200,300,400,500};
		
		int currNum = (int)(Math.random() * 6 + 1) - 1;
		
		return levels[currNum];
		
	}
	
	
	
	//随机获取一个父节点
	public static Long getParentId() throws Exception{
		String sql = "select * from temp_users ";
		Connection con = DBUitil.initConnection();
		ResultSet rs = con.createStatement().executeQuery(sql);
		
		
		int size = 0;
		if(rs != null) {
			rs.last();
			size = rs.getRow();
			rs.first();
		}
		
		if(size == 0) {
			return null;
		}
		
		int currNum = (int)(Math.random() * size + 1);
		//if(currNum == 1) currNum = 0;
		int ct = 0;
		System.out.println("-----------------------------------------------------" + currNum);
		while(rs.next()) {
			
			if(ct == currNum) {
				Long id = rs.getLong("id");
				sql = "update temp_users set status = 0 where id = " + id;
				con.createStatement().execute(sql);
				return id;
			}
			
			ct++;
			
		}
		
		con.close();
		
		return null;
	}
	
	
	
	
	
	
	
	
	public static void addUser(int spid) throws Exception{
		String newName = UUID.randomUUID().toString();
		
		Long pid = 0L;
		
		if(spid == 0) {
			pid = 0L;
		}else {
			pid = getParentId();
			while(pid == null) {
				pid = getParentId();
			}
		}
		
		int level = getUserLevel();
		String sql = "INSERT INTO `temp_users`( `name`, `pid`, `status`,`level`) VALUES ( '"+newName+"', "+pid+", 1 , "+level+")";
		
		Connection con = DBUitil.initConnection();
		Statement stat = con.createStatement();
		
		stat.execute(sql);
		
		stat.close();
		con.close();
	}
	

	

	public static void main(String[] args) {
		
		try {
			int size = 0;
			for(int i = 0 ; i < 2000 ; i++) {
				size ++;
				System.out.println("----ddddd----" + size );
				addUser(5);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		

	}

}
